package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.utils.ConnectionUtils;

public class DeleteSpotService extends HTTPService {

	private static final String REQUEST_URL_SINGLE = "/spots/";
	private static final String REQUEST_URL_MULTI = "/spots/multiple_delete";
	public static final String MULTIPLE_DELETE = "MULTI";
	private static final String DEL_IDS = "spot_ids";
	private Context mContext = this;


	@Override
	protected void onResponse() {
		Intent deleteSpotUIupdate = new Intent(assignedFilter);
		switch (responseStatusCode){
		case HttpStatus.SC_NO_CONTENT: {
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);
			// update UI if active
			deleteSpotUIupdate.putExtra(RESUlT, true);
			sendOrderedBroadcast(deleteSpotUIupdate, null);
			return;
		}
		case HttpStatus.SC_UNAUTHORIZED:
		case HttpStatus.SC_NOT_FOUND:
			JSONObject msg;
			try {
				msg = new JSONObject(responseString);
				onNoResponse(msg.getString(HTTPService.MESSAGE));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		
		}

	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent deleteSpotUIupdate = new Intent(assignedFilter);
		deleteSpotUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(deleteSpotUIupdate, null);
	}

	@Override
	protected HttpRequestBase initRequest() {
		HttpRequestBase req = null;
		if (!extras.getBoolean(MULTIPLE_DELETE)) {
			long id = extras.getLong(Spot.SPOT_ID);
			req = new HttpDelete(API_URL + REQUEST_URL_SINGLE + id);
		}
		else
		{
			req = new HttpPut(API_URL + REQUEST_URL_MULTI);
			try {
				JSONArray idsArray=new JSONArray(extras.getString(Spot.SPOT_ID));
				JSONObject spots=new JSONObject();
				spots.put(DEL_IDS,idsArray);
				((HttpPut) req).setEntity(new ByteArrayEntity(spots.toString().getBytes("UTF-8")));
			} catch (JSONException e) {
					e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
		}
		return req;
	}

}
